package com.test.demoproject.controller;

import com.test.demoproject.entity.Dict;
import com.test.demoproject.service.DemoService;
import com.test.demoproject.service.impl.DemoServiceImpl;
import groovy.lang.Binding;
import groovy.lang.GroovyClassLoader;
import groovy.lang.GroovyShell;
import groovy.lang.Script;
import org.codehaus.groovy.control.CompilerConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.util.List;

@RestController
@RequestMapping("/demo")
public class DemoController {
    @Autowired
    DemoService demoService;

    //之所以能用@Autowired获取到Binding  是因为GroovyBindingConfig类中配置了该bean
    @Autowired
    private Binding groovyBinding;

    private GroovyShell groovyShell;

    @RequestMapping("/select")
    public List<Dict> select(String key){
        List<Dict> list=demoService.select(key);
        return list;
    }

    @PostConstruct
    public void init(){
        GroovyClassLoader groovyClassLoader = new GroovyClassLoader(this.getClass().getClassLoader());
        CompilerConfiguration compilerConfiguration = new CompilerConfiguration();
        compilerConfiguration.setSourceEncoding("utf-8");
        compilerConfiguration.setScriptBaseClass(DemoServiceImpl.class.getName());

        groovyShell = new GroovyShell(groovyClassLoader, groovyBinding, compilerConfiguration);
    }

    @RequestMapping(value = "/execute", method = RequestMethod.POST)
    public List<Dict> execute(@RequestBody String scriptContent) {
        System.out.println(scriptContent);
        Script script = groovyShell.parse(scriptContent);
        List<Dict> dictList = (List)script.run();
        return dictList;
    }

}
